package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/service/model"
	"bgs/util"
	"bgs/wxp/mina"
	"context"
	"encoding/json"
	"fmt"
)

// GenDistributeRequestAuditedNotifyMessage (主动,生成微信小程序消息=>分销员审核结果)
func (s *BrandServiceImp) GenDistributeRequestAuditedNotifyMessage(ctx context.Context, q *sqlc.Queries, brandDistributeRequestID int64) (ret mina.SendNotifyParam, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	brandDistributeRequest, err := q.GetBrandDistributeRequest(ctx, brandDistributeRequestID)
	if err != nil {
		return
	}
	slog.Info("1、读取品牌分销员申请记录 ok")

	brandID := brandDistributeRequest.BrandID
	userID := brandDistributeRequest.UserID
	cBrand := s.cacher.FetchBrand(brandID)
	if cBrand == nil {
		err = fmt.Errorf("not found brand of brandID:%d", brandID)
		return
	}

	user, err := q.GetUser(ctx, userID)
	if err != nil {
		return
	}

	requestContent := fmt.Sprintf("申请成为%s品牌分销员", cBrand.Name)

	var auditResultName string
	switch sqlc.EmAuditResult(brandDistributeRequest.AuditResult) {
	case sqlc.EmAuditResultApproved:
		auditResultName = "通过"
	case sqlc.EmAuditResultRejected:
		auditResultName = "拒绝"
	}

	applyFields := &model.BrandDistributeRequestApplyFields{}
	err = json.Unmarshal(brandDistributeRequest.ApplyFields, applyFields)
	if err != nil {
		err = fmt.Errorf("unmarshal brand_distribute_request apply_fields失败:%s", err.Error())
		return
	}

	ret.Page = fmt.Sprintf("package-common/pages/share-apply-distributor/index?brandId=%d", brandID)
	ret.TemplateID = s.wechatVars.Tp974 //"iGRjZcJSID5XXORdMEwerfmhftD_n9azeIUHBfWaxec"
	ret.UserOpenID = user.OpenID
	ret.MinaState = s.wechatVars.MinaState
	ret.Content = map[string]map[string]interface{}{
		"name10":  {"value": applyFields.NickName},
		"thing9":  {"value": requestContent},
		"phrase5": {"value": auditResultName},
		"date7":   {"value": util.GoTimeToStringf(brandDistributeRequest.Audited.Time, util.LayoutMinute)},
	}

	slog.Infof("生成微信小程序消息=>分销员审核结果 ok")

	return
}
